import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import { RandomCodeGenerator } from '../../../../../util/randomCodeGenerator';
import { RedisInstance } from '../../../../../util/redis';
import mailConfig from '../../../../../config/mail.config';

@Injectable()
export class MailService {
  constructor(
    private mailerService: MailerService,
    private randomCodeGenerator: RandomCodeGenerator,
  ) {}
  async sendEmailCode(body: { toEmail: string }, ip: string) {
    const verificationCode = this.randomCodeGenerator.generateNumCode(6);
    await RedisInstance.initRedis('auth.login', 0);
    const key = `${body.toEmail}_${ip}`;
    await RedisInstance.setRedis(
      'tem.email.code',
      1,
      key,
      `${verificationCode}`,
      5 * 60,
    );
    const sendRes = await this.mailerService.sendMail({
      to: body.toEmail,
      subject: '验证码',
      text: `<div><h1>您好！</h1></div>
      <p>你的短信验证码为${verificationCode},用于修改或者找回密码做的身份验证,5分钟内有效,请勿泄露和转发,如非本人操作,请忽略此邮箱</p>
      `,
    });
    return sendRes;
  }

  async sendEmailToAdmin(body: { emailText: string }) {
    const sendRes = await this.mailerService.sendMail({
      to: mailConfig.subjectEmail,
      subject: '测试邮件',
      text: body.emailText,
    });
    return sendRes;
  }
}
